﻿using Application.ProductTypeService;
using System.Linq;
using Application.SlotServic;
using Domain.Entity;
using Domain.Entity.bs;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;
using Application.WarehouseService;
using Domain.Entity.zct;
using Application.BusinessTypeService;
using Domain.IRepository;

namespace WMSManage.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]//需要鉴权
    public class SlotController : ControllerBase
    {
        private readonly ISlotService slotService;

        private readonly ISlotRepository _slotRepository;
        public SlotController(ISlotService slotService,ISlotRepository slotRepository)
        {
            this.slotService = slotService;
            _slotRepository = slotRepository;
        }


        /// <summary>
        /// 添加库位信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> AddSlot(AddSlotDto addSlotDto)
        {
            return await slotService.AddSlot(addSlotDto);
        }

        // 添加批量添加的接口
        [HttpPost("Batch")]
        public async Task<int> AddSlots([FromBody] List<AddSlotDto> addSlotDtos)
        {
            return await slotService.AddSlot(addSlotDtos);
        }

        /// <summary>
        /// 修改业仓库信息
        /// </summary>
        /// <param name="UpdateSlot"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> UpdateSlot(UpdateSlotDto updateSlotDto)
        {
            return await slotService.UpdateSlot(updateSlotDto);
        }

        /// <summary>
        /// 删除库位信息
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<int> DeleteSlot(int id)
        {
            return await slotService.DeleteSlot(id);
        }

        /// <summary>
        /// 查询仓库主管信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<User>> GetAllUsers()
        {
            return await slotService.GetAllUsers();
        }

        /// <summary>
        /// 分页查询库位信息
        /// </summary>
        /// <param name="currentPage">当前页码</param>
        /// <returns>返回分页结果</returns>
        [HttpGet]
        public async Task<IActionResult> GetSlots(
          int pageSize = 10,
          int currentPage = 1,
          string? code = null,
          string? name = null,
          int? status = null,
          string? userName = null,
          int? warehouseId = null)
        {
            try
            {
                // 确保分页参数有效
                pageSize = Math.Max(pageSize, 1);
                currentPage = Math.Max(currentPage, 1);

                var (list, totalCount) = await _slotRepository.GetSlots(
                    pageSize, currentPage, code, name, status, userName, warehouseId);

                return Ok(new
                {
                    code = 200,
                    message = "success",
                    data = new
                    {
                        list,
                        rows = totalCount,
                        currentPage,
                        pageSize,
                        totalPages = (int)Math.Ceiling(totalCount / (double)pageSize)
                    }
                });
            }
            catch (ApplicationException ex)
            {
                return StatusCode(500, new { code = 500, message = ex.Message });
            }
        }


        /// <summary>
        /// 导入库位信息
        /// </summary>
        [HttpPost("ImportSlots")] // 明确路由路径
            [DisableRequestSizeLimit]
            public async Task<IActionResult> ImportSlots()
            {
                // 1. 验证请求
                if (!Request.HasFormContentType)
                    return BadRequest(new { success = false, message = "请求必须包含表单数据" });

                var form = await Request.ReadFormAsync();
                var file = form.Files["file"];

                if (file == null || file.Length == 0)
                    return BadRequest(new { success = false, message = "请上传有效的Excel文件" });

                // 2. 验证文件类型
                var allowedTypes = new[] {
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    "application/vnd.ms-excel"
                };
                if (!allowedTypes.Contains(file.ContentType))
                    return BadRequest(new { success = false, message = "只支持.xlsx或.xls格式的Excel文件" });

                // 3. 处理文件
                try
                {
                    using var stream = new MemoryStream();
                    await file.CopyToAsync(stream);
                    stream.Position = 0;

                    using var package = new ExcelPackage(stream);
                    var worksheet = package.Workbook.Worksheets[0];

                    if (worksheet.Dimension == null)
                        return BadRequest(new { success = false, message = "Excel文件中没有数据" });

                    // 4. 读取表头验证
                    var headers = Enumerable.Range(1, worksheet.Dimension.Columns)
                        .Select(col => worksheet.Cells[1, col].Value?.ToString()?.Trim())
                        .ToList();

                    // 修改为更灵活的列名匹配（不区分大小写和空格）
                    var requiredColumns = new[] { "序号", "库位编号", "库位名称", "库位容量/m³", "仓库主管", "排序", "库位状态", "备注" };
                    foreach (var column in requiredColumns)
                    {
                        if (!headers.Any(h => h?.ToLower() == column.ToLower()))
                            return BadRequest(new
                            {
                                success = false,
                                message = $"Excel文件中缺少必要的列: '{column}'"
                            });
                    }


                    // 6. 处理数据行
                    var result = new ImportResult
                    {
                        SuccessCount = 0,
                        DuplicateCount = 0,
                        Errors = new List<string>()
                    };

                    for (int row = 2; row <= worksheet.Dimension.Rows; row++)
                    {
                        try
                        {
                            var slot = new Slot();
                            bool isValid = true;

                            // 读取各列数据
                            for (int col = 1; col <= worksheet.Dimension.Columns; col++)
                            {
                                var header = headers[col - 1];
                                var value = worksheet.Cells[row, col].Value?.ToString()?.Trim();

                                try
                                {
                                    // 更灵活的列名匹配
                                    switch (header?.ToLower())
                                    {
                                        case "库位编号":
                                            if (string.IsNullOrEmpty(value))
                                            {
                                                result.Errors.Add($"第{row}行: 库位编号不能为空");
                                                isValid = false;
                                            }
                                            slot.slot_code = value;
                                            break;
                                        case "库位名称":
                                            if (string.IsNullOrEmpty(value))
                                            {
                                                result.Errors.Add($"第{row}行: 库位名称不能为空");
                                                isValid = false;
                                            }
                                            slot.slot_name = value;
                                            break;
                                        case "库位容量/m³":
                                            if (string.IsNullOrEmpty(value))
                                            {
                                                result.Errors.Add($"第{row}行: 库位容量不能为空");
                                                isValid = false;
                                            }
                                            else if (!int.TryParse(value, out int capacity) || capacity <= 0)
                                            {
                                                result.Errors.Add($"第{row}行: 库位容量必须是大于0的整数");
                                                isValid = false;
                                            }
                                            else
                                            {
                                                slot.slot_capacity = capacity;
                                            }
                                            break;
                                        case "仓库主管":
                                            if (string.IsNullOrEmpty(value))
                                            {
                                                result.Errors.Add($"第{row}行: 库位主管不能为空");
                                                isValid = false;
                                            }
                                            // 这里应该存储用户ID而不是用户名，需要调整
                                            slot.slot_userName = value;
                                            break;

                                        case "排序":
                                            if (string.IsNullOrEmpty(value) || !int.TryParse(value, out int sort) || sort < 0)
                                            {
                                                result.Errors.Add($"第{row}行: 排序必须是大于等于0的整数");
                                                isValid = false;
                                            }
                                            else
                                            {
                                                slot.slot_sort = sort;
                                            }
                                            break;
                                        case "库位状态":
                                            if (string.IsNullOrEmpty(value))
                                            {
                                                result.Errors.Add($"第{row}行: 库位状态不能为空");
                                                isValid = false;
                                            }
                                            else
                                            {
                                                switch (value.ToLower())
                                                {
                                                    case "正常":
                                                    case "启用":
                                                    case "1":
                                                    case "true":
                                                        slot.slot_status = 0;
                                                        break;
                                                    case "停用":
                                                    case "0":
                                                    case "false":
                                                        slot.slot_status = 1;
                                                        break;
                                                    default:
                                                        result.Errors.Add($"第{row}行: 库位状态值无效，必须是 '正常'/'启用' 或 '停用'");
                                                        isValid = false;
                                                        break;
                                                }
                                            }
                                            break;

                                        case "备注":
                                            slot.remark = value;
                                            break;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    result.Errors.Add($"第{row}行 '{header}' 格式错误: {ex.Message}");
                                    isValid = false;
                                }
                            }

                            if (!isValid) continue;


                            // 构建DTO并插入数据库
                            var dto = new AddSlotDto
                            {
                                slot_code = slot.slot_code,
                                slot_name = slot.slot_name,
                                slot_capacity = slot.slot_capacity,
                                slot_userName = slot.slot_userName, // 注意：这里应该存储用户ID
                                slot_sort = slot.slot_sort,
                                slot_status = slot.slot_status,
                                remark = slot.remark,
                                is_delete=0
                            };

                            try
                            {
                                var addResult = await slotService.AddSlot(dto);
                                if (addResult > 0)
                                {
                                    result.SuccessCount++;
                       
                                }
                                else
                                {
                                    result.Errors.Add($"第{row}行: 数据库插入失败");
                                }
                            }
                            catch (Exception ex)
                            {
                                result.Errors.Add($"第{row}行: 数据库异常 - {ex.Message}");
                            }
                        }
                        catch (Exception ex)
                        {
                            result.Errors.Add($"第{row}行处理失败: {ex.Message}");
                        }
                    }

                    return Ok(result);
                }
                catch (Exception ex)
                {
       
                    return StatusCode(500, new
                    {
                        success = false,
                        message = "服务器处理文件时出错",
                        error = ex.Message
                    });
                }
            }

            // 导入结果模型
            public class ImportResult
            {
                public int SuccessCount { get; set; }
                public int DuplicateCount { get; set; }
                public List<string> Errors { get; set; }
            }


        /// <summary>
        /// 根据仓库id查询对应库位
        /// </summary>
        /// <param name="whid"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<Slot>> GetSlotsByWhid(int whid)
        {
            return await slotService.GetSlotsByWhid(whid);
        }

    }
}
